package com.simonmacdonald.cordova.plugins;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog;
import android.telephony.TelephonyManager;
import android.util.Log;

public class TelephoneNumber extends CordovaPlugin {

	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) {
		if (action.equals("get")) {
			// TelephonyManager telephonyManager =
			// (TelephonyManager)this.cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
			// String result = telephonyManager.getLine1Number();
			JSONObject result = null;
			try {
				result = getCallListing();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (result != null) {
				callbackContext.sendPluginResult(new PluginResult(
						PluginResult.Status.OK, result));
				return true;
			}
		}
		callbackContext.sendPluginResult(new PluginResult(
				PluginResult.Status.ERROR));
		return false;
	}

	private JSONObject getCallListing() throws JSONException {

		JSONObject callLog = new JSONObject();

		String[] strFields = {

		android.provider.CallLog.Calls.NUMBER,
				android.provider.CallLog.Calls.CACHED_NAME, };

		try {
			/*
			 * Cursor callLogCursor =
			 * cordova.getActivity().getContentResolver().query(
			 * android.provider.CallLog.Calls.CONTENT_URI, strFields,
			 * CallLog.Calls.DATE + ">?", // new String[] {period}, new
			 * String[]{ String.valueOf(CallLog.Calls.OUTGOING_TYPE) },
			 * android.provider.CallLog.Calls.DEFAULT_SORT_ORDER +" Limit 100");
			 */
			Cursor callLogCursor = cordova
					.getActivity()
					.getContentResolver()
					.query(android.provider.CallLog.Calls.CONTENT_URI,
							strFields,
							CallLog.Calls.DATE + ">?",
							// new String[] {period},
							new String[] { String
									.valueOf(CallLog.Calls.OUTGOING_TYPE) },
							android.provider.CallLog.Calls.DEFAULT_SORT_ORDER
									+ " Limit 100");

			int callCount = callLogCursor.getCount();

			if (callCount > 0) {
				JSONObject callLogItem = new JSONObject();
				JSONArray callLogItems = new JSONArray();

				callLogCursor.moveToFirst();
				do {
					callLogItem.put("number", callLogCursor.getString(0));
					callLogItem.put("cachedName", callLogCursor.getString(1));

					callLogItems.put(callLogItem);
					callLogItem = new JSONObject();
				} while (callLogCursor.moveToNext());
				callLog.put("rows", callLogItems);
				System.out.println("CALLLOG" + callLogItems);
			}

			callLogCursor.close();
		} catch (Exception e) {
			Log.d("CallLog_Plugin",
					" ERROR : SQL to get cursor: ERROR " + e.getMessage());
		}

		return callLog;
	}

}
